//
//  XYUserAccountViewModel.swift
//  01.XinLangWB
//
//  Created by 肖玉东 on 16/4/19.
//  Copyright © 2016年 苏小样. All rights reserved.
//

import UIKit
private let userInfoKey = "com.itheima.userInfoKey"
class XYUserAccountViewModel: NSObject {
    //创建一个单利
    static let shareAccountModel: XYUserAccountViewModel = XYUserAccountViewModel()
    var userAccount : XYUserAccount?
    //添加一个计算属性(只读属性)
    var userLogin: Bool {
        //1.UserAccount的token 如果不为空 && 用户token不过期 用户已经登录
    
        if let u = userAccount where u.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return true
        }
        //将userAccount 设置为 nil
        userAccount = nil
        return false
    }
    //增加一个用户头像NSURL 类型的属性
    var headImageURL: NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    
    
    //私有化构造方法
    private override init() {
        super.init()
     userAccount = self.loadUserInfo()
    }
    
    //MARK:使用授权码获取accesstoken
    func loadAccessToken(code: String,finished:(isSucceed: Bool)->()){
        HMNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                print(error)
                //TODO: 一会儿完善
                finished(isSucceed: false)
                // SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
                return
        }
                   //程序走到这里就一定成功
            print("授权成功")
            //获取用户信息 在请求的回调中 再去获取用户的信息
            self.loadUserInfo(result!,finished: finished)
            
        }
    }
    //token uid
    private func loadUserInfo(result: AnyObject,finished:(isSucceed: Bool)->()){
        //尝试将AnyObject 转换成字典
        guard let dict = result as? [String:AnyObject] else{
            // SVProgressHUD.showErrorWithStatus("数据错误")
            finished(isSucceed: false)
            return
        }
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        HMNetworkTools.sharedTools.loadUserInfo(token, uid: uid) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(isSucceed: false)
                // SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
                return
        }
                    print("获取用户信息成功")
            
            //将用户的数据保存起来 ,将AnyObject转为字典
            guard var userInfoDict = result as? [String:AnyObject] else {
                // SVProgressHUD.showErrorWithStatus("数据错误")
                finished(isSucceed: false)
                return
            }
            //遍历字典
            for (k,v) in dict{
                userInfoDict[k] = v
            }
            print(userInfoDict)
           self.saveUserAccount(userInfoDict)
                        //执行成功的回调
            finished(isSucceed: true)
            
        }
    }

}
//存储数据 , 获取数据
extension XYUserAccountViewModel{
    
    func saveUserAccount(userInfoDict: [String: AnyObject]){
        ////保存完整的字典信息  偏好设置中不能保存nil
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        //将字典转为模型
        let accout = XYUserAccount(dict: userInfoDict)
        //给单例对象的用户账户模型属性赋值,为了解决从未登录状态到登录状态用户账户模型为空的问题
        self.userAccount = accout
        //获取模型对应字典的信息
        let keys = ["access_token","avatar_large","name","expires_in","uid","expires_date"]
        let accoutDict = accout.dictionaryWithValuesForKeys(keys)
        //将对象的字典信息保存到偏好设置中
        userDefaults.setObject(accoutDict, forKey: userInfoKey)
        //同步
        userDefaults.synchronize()

    }
    //获取沙盒中存储的数据
    func loadUserInfo() -> XYUserAccount?{
        //获取字典的信息
        guard  let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey)  as? [String: AnyObject] else{
            return nil
        }
        //将字典转换成模型
        let account = XYUserAccount(dict: dict)
        return account
    }
    
}
